<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
<meta name="google-site-verification" content="SByO7HWUKwufO-witstBrFt-yyK6q3tUlCyYwkvYPiQ" />
<meta name="baidu-site-verification" content="orhaMjPwcS" />
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"lixiyan4633.gitee.io","root":"/","scheme":"Pisces","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="数据结构算法打卡，参考的王铮老师在极客时间上的《数据结构与算法之美》">
<meta property="og:type" content="article">
<meta property="og:title" content="数据结构算法Day16-堆">
<meta property="og:url" content="https://lixiyan4633.gitee.io/2020/03/30/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E7%AE%97%E6%B3%95Day16-%E5%A0%86/index.html">
<meta property="og:site_name" content="喜延的个人博客">
<meta property="og:description" content="数据结构算法打卡，参考的王铮老师在极客时间上的《数据结构与算法之美》">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://static001.geekbang.org/resource/image/4c/99/4c452a1ad3b2d152daa2727d06097099.jpg">
<meta property="og:image" content="https://static001.geekbang.org/resource/image/4d/1e/4d349f57947df6590a2dd1364c3b0b1e.jpg">
<meta property="og:image" content="https://static001.geekbang.org/resource/image/e5/22/e578654f930002a140ebcf72b11eb722.jpg">
<meta property="og:image" content="https://static001.geekbang.org/resource/image/e3/0e/e3744661e038e4ae570316bc862b2c0e.jpg">
<meta property="og:image" content="https://static001.geekbang.org/resource/image/59/81/5916121b08da6fc0636edf1fc24b5a81.jpg">
<meta property="og:image" content="https://static001.geekbang.org/resource/image/11/60/110d6f442e718f86d2a1d16095513260.jpg">
<meta property="og:image" content="https://static001.geekbang.org/resource/image/50/1e/50c1e6bc6fe68378d0a66bdccfff441e.jpg">
<meta property="og:image" content="https://static001.geekbang.org/resource/image/aa/9d/aabb8d15b1b92d5e040895589c60419d.jpg">
<meta property="og:image" content="https://static001.geekbang.org/resource/image/89/d5/899b9f1b40302c9bd5a7f77f042542d5.jpg">
<meta property="og:image" content="https://static001.geekbang.org/resource/image/f7/09/f712f8a7baade44c39edde839cefcc09.jpg">
<meta property="og:image" content="https://static001.geekbang.org/resource/image/62/df/629328315decd96e349d8cb3940636df.jpg">
<meta property="og:image" content="https://static001.geekbang.org/resource/image/46/36/46ca25edc69b556b967d2c62388b7436.jpg">
<meta property="og:image" content="https://static001.geekbang.org/resource/image/23/d1/23958f889ca48dbb8373f521708408d1.jpg">
<meta property="og:image" content="https://static001.geekbang.org/resource/image/b0/e7/b04656d27fd0ba112a38a28c892069e7.jpg">
<meta property="article:published_time" content="2020-03-30T02:42:10.000Z">
<meta property="article:modified_time" content="2020-03-30T05:58:53.199Z">
<meta property="article:author" content="李喜延">
<meta property="article:tag" content="数据结构">
<meta property="article:tag" content="算法">
<meta property="article:tag" content="堆">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://static001.geekbang.org/resource/image/4c/99/4c452a1ad3b2d152daa2727d06097099.jpg">

<link rel="canonical" href="https://lixiyan4633.gitee.io/2020/03/30/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E7%AE%97%E6%B3%95Day16-%E5%A0%86/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>数据结构算法Day16-堆 | 喜延的个人博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">喜延的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">我的大数据的之路</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://lixiyan4633.gitee.io/2020/03/30/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E7%AE%97%E6%B3%95Day16-%E5%A0%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://tva1.sinaimg.cn/large/00831rSTly1gcyel996b4j30oa0oc1kx.jpg">
      <meta itemprop="name" content="李喜延">
      <meta itemprop="description" content="愿世界和平">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="喜延的个人博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          数据结构算法Day16-堆
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-03-30 10:42:10 / 修改时间：13:58:53" itemprop="dateCreated datePublished" datetime="2020-03-30T10:42:10+08:00">2020-03-30</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" itemprop="url" rel="index"><span itemprop="name">数据结构</span></a>
                </span>
            </span>

          
            <div class="post-description">数据结构算法打卡，参考的王铮老师在极客时间上的《数据结构与算法之美》<br> <img src="https://static001.geekbang.org/resource/image/fd/b2/fdd7e83c7816075a638f02f97558fbb2.jpg"></div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="1-概念"><a href="#1-概念" class="headerlink" title="1.概念"></a>1.概念</h1><p>“堆”（Heap）。堆这种数据结构的应用场景非常多，最经典的莫过于堆排序了。堆排序是一种原地的、时间复杂度为 O(nlogn) 的排序算法，快排也是O(nlogn)，在实际的软件开发中，快速排序的性能要比堆排序好，这是为什么呢？</p>
<ul>
<li><p>堆是一个完全二叉树；</p>
</li>
<li><p>堆中每一个节点的值都必须大于等于（或小于等于）其子树中每个节点的值。</p>
</li>
</ul>
<p><img src="https://static001.geekbang.org/resource/image/4c/99/4c452a1ad3b2d152daa2727d06097099.jpg" alt="img"></p>
<p>1-2是大顶堆，3是小顶堆，4不是，因为不是完全二叉树</p>
<h1 id="2-堆的实现"><a href="#2-堆的实现" class="headerlink" title="2.堆的实现"></a>2.堆的实现</h1><h2 id="2-1-数组方式"><a href="#2-1-数组方式" class="headerlink" title="2.1 数组方式"></a>2.1 数组方式</h2><p><img src="https://static001.geekbang.org/resource/image/4d/1e/4d349f57947df6590a2dd1364c3b0b1e.jpg" alt="img"></p>
<p>数组中下标为 i 的节点:</p>
<ul>
<li><p>左子节点，就是下标为 i∗2 的节点</p>
</li>
<li><p>右子节点就是下标为 i∗2+1 的节点</p>
</li>
<li><p>父节点就是下标为 i/2 的节点。</p>
</li>
</ul>
<h2 id="2-2-往堆中插入一个元素"><a href="#2-2-往堆中插入一个元素" class="headerlink" title="2.2 往堆中插入一个元素"></a>2.2 往堆中插入一个元素</h2><p>堆化：就是顺着节点所在的路径，向上或者向下，对比，然后交换。</p>
<p><img src="https://static001.geekbang.org/resource/image/e5/22/e578654f930002a140ebcf72b11eb722.jpg" alt="堆插入22"></p>
<p>堆化过程</p>
<p><img src="https://static001.geekbang.org/resource/image/e3/0e/e3744661e038e4ae570316bc862b2c0e.jpg" alt="堆化过程"></p>
<p>堆化的代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Heap</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">int</span>[] a; <span class="comment">// 数组，从下标1开始存储数据</span></span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">int</span> n;  <span class="comment">// 堆可以存储的最大数据个数</span></span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">int</span> count; <span class="comment">// 堆中已经存储的数据个数</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">Heap</span><span class="params">(<span class="keyword">int</span> capacity)</span> </span>&#123;</span><br><span class="line">    a = <span class="keyword">new</span> <span class="keyword">int</span>[capacity + <span class="number">1</span>];</span><br><span class="line">    n = capacity;</span><br><span class="line">    count = <span class="number">0</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">insert</span><span class="params">(<span class="keyword">int</span> data)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (count &gt;= n) <span class="keyword">return</span>; <span class="comment">// 堆满了</span></span><br><span class="line">    ++count;</span><br><span class="line">    a[count] = data;</span><br><span class="line">    <span class="keyword">int</span> i = count;</span><br><span class="line">    <span class="keyword">while</span> (i/<span class="number">2</span> &gt; <span class="number">0</span> &amp;&amp; a[i] &gt; a[i/<span class="number">2</span>]) &#123; <span class="comment">// 自下往上堆化</span></span><br><span class="line">      swap(a, i, i/<span class="number">2</span>); <span class="comment">// swap()函数作用：交换下标为i和i/2的两个元素</span></span><br><span class="line">      i = i/<span class="number">2</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-3-堆中删除堆顶元素"><a href="#2-3-堆中删除堆顶元素" class="headerlink" title="2.3 堆中删除堆顶元素"></a>2.3 堆中删除堆顶元素</h2><p>如果大顶堆删除堆顶元素，需要从左或右节点移动上来，依次类推，知道符合堆的特性</p>
<p><img src="https://static001.geekbang.org/resource/image/59/81/5916121b08da6fc0636edf1fc24b5a81.jpg" alt="img"></p>
<p>找到堆的最下层的元素【数组的最后一个count的元素即可】，然后替换堆顶元素，然后堆化</p>
<p><img src="https://static001.geekbang.org/resource/image/11/60/110d6f442e718f86d2a1d16095513260.jpg" alt="img"></p>
<p>代码实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">removeMax</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (count == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    a[<span class="number">1</span>] = a[count];</span><br><span class="line">    --count;</span><br><span class="line">    heapify(a, count, <span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 自上往下堆化</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">heapify</span><span class="params">(<span class="keyword">int</span>[] a, <span class="keyword">int</span> n, <span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">        <span class="keyword">int</span> maxPos = i;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (i * <span class="number">2</span> &lt;= n &amp;&amp; a[i] &lt; a[i * <span class="number">2</span>]) &#123;</span><br><span class="line">            maxPos = i * <span class="number">2</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (i * <span class="number">2</span> + <span class="number">1</span> &lt;= n &amp;&amp; a[maxPos] &lt; a[i * <span class="number">2</span> + <span class="number">1</span>]) &#123;</span><br><span class="line">            maxPos = i * <span class="number">2</span> + <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (maxPos == i) &#123;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        swap(a, i, maxPos);</span><br><span class="line">        i = maxPos;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>堆化的复杂度O(log(n))，插入数据和删除堆顶元素的主要逻辑就是堆化，所以，往堆中插入一个元素和删除堆顶元素的时间复杂度都是 O(logn)。</p>
<h1 id="3-堆的操作"><a href="#3-堆的操作" class="headerlink" title="3.堆的操作"></a>3.堆的操作</h1><p>堆排序的过程大致分解成两个大的步骤，建堆和排序。</p>
<h2 id="1-建堆"><a href="#1-建堆" class="headerlink" title="1.建堆"></a>1.建堆</h2><p>思路一：在堆中插入一个元素的思路，将下标从 2 到 n 的数据依次插入到堆中。这样我们就将包含 n 个数据的数组，组织成了堆。</p>
<p>思路二：跟第一种截然相反，因为叶子节点往下堆化只能自己跟自己比较，所以我们直接从<strong>第一个非叶子节点</strong>开始，依次堆化就行了。思路如下图所示</p>
<p><img src="https://static001.geekbang.org/resource/image/50/1e/50c1e6bc6fe68378d0a66bdccfff441e.jpg" alt="img"></p>
<p><img src="https://static001.geekbang.org/resource/image/aa/9d/aabb8d15b1b92d5e040895589c60419d.jpg" alt="img"></p>
<p>代码实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/***</span></span><br><span class="line"><span class="comment"> * 建堆</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> a 数组</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> n 数组大小</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">buildHeap</span><span class="params">(<span class="keyword">int</span>[] a, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// i是 节点下标</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = n / <span class="number">2</span>; i &gt;= <span class="number">1</span>; --i) &#123;</span><br><span class="line">        heapify(a, n, i);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 自上往下堆化</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">heapify</span><span class="params">(<span class="keyword">int</span>[] a, <span class="keyword">int</span> n, <span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">        <span class="keyword">int</span> maxPos = i;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (i * <span class="number">2</span> &lt;= n &amp;&amp; a[i] &lt; a[i * <span class="number">2</span>]) &#123;</span><br><span class="line">            maxPos = i * <span class="number">2</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (i * <span class="number">2</span> + <span class="number">1</span> &lt;= n &amp;&amp; a[maxPos] &lt; a[i * <span class="number">2</span> + <span class="number">1</span>]) &#123;</span><br><span class="line">            maxPos = i * <span class="number">2</span> + <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (maxPos == i) &#123;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        swap(a, i, maxPos);</span><br><span class="line">        i = maxPos;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>建立堆的时间复杂度O(n)</strong></p>
<p>我们只需要将每个节点的高度求和，得出的就是建堆的时间复杂度。</p>
<p><img src="https://static001.geekbang.org/resource/image/89/d5/899b9f1b40302c9bd5a7f77f042542d5.jpg" alt="img"></p>
<p>我们将每个非叶子节点的高度求和，就是下面这个公式：</p>
<p><img src="https://static001.geekbang.org/resource/image/f7/09/f712f8a7baade44c39edde839cefcc09.jpg" alt="img"></p>
<p>把公式左右都乘以 2，就得到另一个公式 S2。我们将 S2 错位对齐，并且用 S2 减去 S1，可以得到 S。</p>
<p><img src="https://static001.geekbang.org/resource/image/62/df/629328315decd96e349d8cb3940636df.jpg" alt="img"></p>
<p>S 的中间部分是一个等比数列，所以最后可以用等比数列的求和公式来计算，最终的结果就是下面图中画的这个样子。</p>
<p><img src="https://static001.geekbang.org/resource/image/46/36/46ca25edc69b556b967d2c62388b7436.jpg" alt="img"></p>
<p>因为 h=log2n，代入公式 S，就能得到 S=O(n)，所以，建堆的时间复杂度就是 O(n)。</p>
<h2 id="2-排序"><a href="#2-排序" class="headerlink" title="2.排序"></a>2.排序</h2><p>因为是大顶堆，所以最大的元素就是堆顶，这个过程有点类似上面讲的“删除堆顶元素”的操作，当堆顶元素移除之后，我们把下标为 n 的元素放到堆顶，然后再通过堆化的方法，将剩下的 n−1 个元素重新构建成堆。堆化完成之后，我们再取堆顶的元素，放到下标是 n−1 的位置，一直重复这个过程，直到最后堆中只剩下标为 1 的一个元素，排序工作就完成了。</p>
<p><img src="https://static001.geekbang.org/resource/image/23/d1/23958f889ca48dbb8373f521708408d1.jpg" alt="排序过程"></p>
<p>代码实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/***</span></span><br><span class="line"><span class="comment"> * 排序</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> a 数组</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> n 数组长度</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">sort</span><span class="params">(<span class="keyword">int</span>[] a, <span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">    buildHeap(a, n);</span><br><span class="line">    <span class="keyword">int</span> k = n;</span><br><span class="line">    <span class="keyword">while</span> (k &gt; <span class="number">1</span>) &#123;</span><br><span class="line">        swap(a, <span class="number">1</span>, k);</span><br><span class="line">        --k;</span><br><span class="line">        heapify(a, k, <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>排序复杂度分析：</strong></p>
<p>整个堆排序的过程，都只需要极个别临时存储空间，所以堆排序是<strong>原地排序算法</strong>。堆排序包括建堆和排序两个操作，建堆过程的时间复杂度是 O(n)，排序过程的时间复杂度是 O(nlogn)，所以，堆排序整体的时间复杂度是 O(nlogn)。</p>
<p>堆排序<strong>不是稳定的排序算法</strong>，因为在排序的过程，存在将堆的最后一个节点跟堆顶节点互换的操作，所以就有可能改变值相同数据的原始相对顺序。</p>
<h1 id="4-堆应用"><a href="#4-堆应用" class="headerlink" title="4.堆应用"></a>4.堆应用</h1><h2 id="堆的应用一：优先级队列"><a href="#堆的应用一：优先级队列" class="headerlink" title="堆的应用一：优先级队列"></a>堆的应用一：优先级队列</h2><p>一个堆就可以看成是一个优先级队列，插入的元素按照优先级排序，堆顶就是最高(或最低)优先级的元素</p>
<p><strong>1.合并文件：</strong></p>
<p>一个大文件分为10个小文件，每个文件都是按照字符串顺序的，取出每个文件的第一个字符，比较放入数组，取堆顶元素，依次放入大文件当中，找文件最小字符的时间复杂度为O(logn).</p>
<p><strong>2.高性能定时器</strong></p>
<p>如果有一批待执行的定时任务，定时器每过一个很小的单位时间（比如 1 秒），就扫描一遍任务，看是否有任务到达设定的执行时间。如果到达了，就拿出来执行。</p>
<p>比较低效，主要原因有两点：</p>
<p>第一，任务的约定执行时间离当前时间可能还有很久，这样前面很多次扫描其实都是徒劳的；</p>
<p>第二，每次都要扫描整个任务列表，如果任务列表很大的话，势必会比较耗时。</p>
<p><img src="https://static001.geekbang.org/resource/image/b0/e7/b04656d27fd0ba112a38a28c892069e7.jpg" alt="img"></p>
<p>改进：</p>
<p>用优先级队列来解决。我们按照任务设定的执行时间，将这些任务存储在优先级队列中，队列首部（也就是小顶堆的堆顶）存储的是最先执行的任务。</p>
<p>这样就不用每次扫描整个任务队列，也不用频繁扫描，求出当前时间和堆顶时间间隔，然后触发就行了。</p>
<h2 id="堆的应用二：利用堆求-Top-K"><a href="#堆的应用二：利用堆求-Top-K" class="headerlink" title="堆的应用二：利用堆求 Top K"></a>堆的应用二：利用堆求 Top K</h2><p>维护一个k大小的小顶堆，然后和数组元素一次比较，如果大的话，就插入堆顶，如果小就不处理</p>
<p>遍历数组需要 O(n) 的时间复杂度，一次堆化操作需要 O(logK) 的时间复杂度，所以最坏情况下，n 个元素都入堆一次，时间复杂度就是 O(nlogK)。</p>
<h1 id="5-问题"><a href="#5-问题" class="headerlink" title="5.问题"></a>5.问题</h1><h2 id="1-为什么快速排序要比堆排序性能好？"><a href="#1-为什么快速排序要比堆排序性能好？" class="headerlink" title="1.为什么快速排序要比堆排序性能好？"></a>1.为什么快速排序要比堆排序性能好？</h2><p><strong>第一点，堆排序数据访问的方式没有快速排序友好。</strong></p>
<p>对于快速排序来说，数据是顺序访问的。而对于堆排序来说，数据是跳着访问的。</p>
<p>比如，堆排序中，最重要的一个操作就是数据的堆化。比如下面这个例子，对堆顶节点进行堆化，会依次访问数组下标是 1，2，4，8 的元素，而不是像快速排序那样，局部顺序访问，所以，这样对 CPU 缓存是不友好的。</p>
<p><strong>第二点，对于同样的数据，在排序过程中，堆排序算法的数据交换次数要多于快速排序。</strong></p>
<p>但是堆排序的第一步是建堆，建堆的过程会打乱数据原有的相对先后顺序，导致原数据的有序度降低。比如，对于一组已经有序的数据来说，经过建堆之后，数据反而变得更无序了。</p>
<h2 id="2-给定1G磁盘，假设现在我们有一个包含-10-亿个搜索关键词的日志文件，如何快速获取到-Top-10-最热门的搜索关键词呢？"><a href="#2-给定1G磁盘，假设现在我们有一个包含-10-亿个搜索关键词的日志文件，如何快速获取到-Top-10-最热门的搜索关键词呢？" class="headerlink" title="2.给定1G磁盘，假设现在我们有一个包含 10 亿个搜索关键词的日志文件，如何快速获取到 Top 10 最热门的搜索关键词呢？"></a>2.给定1G磁盘，假设现在我们有一个包含 10 亿个搜索关键词的日志文件，如何快速获取到 Top 10 最热门的搜索关键词呢？</h2><p>1.MapReduce</p>
<p>2.散列表+堆排序</p>
<p>如果重复就在散列表的值+1，如果没有就插入</p>
<p>然后建立10位的小顶堆，然后和堆顶比较，如果大的话，就删除堆顶元素，并插入数据，求出top10</p>
<p>如果散列表空间不够，就按照词的hashcode分到10个文件，每个文件1亿关键词，然后分别求出每个文件的topk,然后最后比较10个top10的top10</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" rel="tag"><i class="fa fa-tag"></i> 数据结构</a>
              <a href="/tags/%E7%AE%97%E6%B3%95/" rel="tag"><i class="fa fa-tag"></i> 算法</a>
              <a href="/tags/%E5%A0%86/" rel="tag"><i class="fa fa-tag"></i> 堆</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/03/29/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E7%AE%97%E6%B3%95Day15-%E9%80%92%E5%BD%92%E6%A0%91/" rel="prev" title="数据结构算法Day15-递归树">
      <i class="fa fa-chevron-left"></i> 数据结构算法Day15-递归树
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/03/31/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E7%AE%97%E6%B3%95Day17-%E5%9B%BE/" rel="next" title="数据结构算法Day17-图">
      数据结构算法Day17-图 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  
<div>
    
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------　　　　本文结束　<i class="fa fa-heart"></i>　感谢您的阅读　　　　-------------</div>
    
</div>


    
 </div>

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-概念"><span class="nav-number">1.</span> <span class="nav-text">1.概念</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-堆的实现"><span class="nav-number">2.</span> <span class="nav-text">2.堆的实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-数组方式"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 数组方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-往堆中插入一个元素"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 往堆中插入一个元素</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-3-堆中删除堆顶元素"><span class="nav-number">2.3.</span> <span class="nav-text">2.3 堆中删除堆顶元素</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-堆的操作"><span class="nav-number">3.</span> <span class="nav-text">3.堆的操作</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-建堆"><span class="nav-number">3.1.</span> <span class="nav-text">1.建堆</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-排序"><span class="nav-number">3.2.</span> <span class="nav-text">2.排序</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-堆应用"><span class="nav-number">4.</span> <span class="nav-text">4.堆应用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#堆的应用一：优先级队列"><span class="nav-number">4.1.</span> <span class="nav-text">堆的应用一：优先级队列</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#堆的应用二：利用堆求-Top-K"><span class="nav-number">4.2.</span> <span class="nav-text">堆的应用二：利用堆求 Top K</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5-问题"><span class="nav-number">5.</span> <span class="nav-text">5.问题</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-为什么快速排序要比堆排序性能好？"><span class="nav-number">5.1.</span> <span class="nav-text">1.为什么快速排序要比堆排序性能好？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-给定1G磁盘，假设现在我们有一个包含-10-亿个搜索关键词的日志文件，如何快速获取到-Top-10-最热门的搜索关键词呢？"><span class="nav-number">5.2.</span> <span class="nav-text">2.给定1G磁盘，假设现在我们有一个包含 10 亿个搜索关键词的日志文件，如何快速获取到 Top 10 最热门的搜索关键词呢？</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="李喜延"
      src="https://tva1.sinaimg.cn/large/00831rSTly1gcyel996b4j30oa0oc1kx.jpg">
  <p class="site-author-name" itemprop="name">李喜延</p>
  <div class="site-description" itemprop="description">愿世界和平</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">25</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">25</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">李喜延</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
